package com.dingtalk.yuanhua_spring_project.service.impl;

import com.aliyun.dingtalkyida_1_0.models.GetInstanceByIdHeaders;
import com.aliyun.dingtalkyida_1_0.models.GetInstanceByIdRequest;
import com.aliyun.dingtalkyida_2_0.Client;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataIdListHeaders;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataIdListRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.yuanhua_spring_project.service.DingTalkYiDa;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DingTalkYiDaimpl implements DingTalkYiDa {
    private static final Logger logger = LoggerFactory.getLogger(DingTalkYiDaimpl.class);

    private static com.aliyun.dingtalkyida_2_0.Client createClient2() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkyida_2_0.Client(config);
    }

    public static com.aliyun.dingtalkyida_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkyida_1_0.Client(config);
    }

    /**
     * 根据表单ID获取表单实例ID列表
     * @return List<String>
     *     * @param accessToken 许可
     *     *     * @param appType 应用编码
     *     *     * @param formUuid 表单实例ID
     *     *     * @param userId 用户ID
     *     *     * @param systemToken 应用密钥
     * **/

    public  List<String> getInstaceIdList1(String accessToken, String appType, String formUuid, String userId, String systemToken) throws Exception {
        com.aliyun.dingtalkyida_1_0.Client client = createClient();
        GetInstanceByIdHeaders getInstanceByIdHeaders = new GetInstanceByIdHeaders();
        getInstanceByIdHeaders.xAcsDingtalkAccessToken = accessToken;
        GetInstanceByIdRequest getInstanceByIdRequest = new GetInstanceByIdRequest()
                .setAppType(appType)
                .setSystemToken(systemToken)
                .setUserId(userId)
                .setLanguage("zh_CN");
        try {
            var response = client.getInstanceByIdWithOptions(formUuid, getInstanceByIdRequest, getInstanceByIdHeaders, new RuntimeOptions());
            var body = response.getBody().getData();
            System.out.println(body);
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                logger.error("getInstaceIdList1 Error code: {}, Error message: {}", err.code, err.message, err);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
        return null;
    }

    public List<String> getInstanceIdList(String accessToken, String appType, String formUuid, String userId, String systemToken) throws Exception {
        List<String> instanceIdList = new ArrayList<>();
        Client client = createClient2();
        SearchFormDataIdListHeaders searchFormDataIdListHeaders = new SearchFormDataIdListHeaders();
        searchFormDataIdListHeaders.xAcsDingtalkAccessToken = accessToken;
        int pageNumber = 1;
        int pageSize = 20;

        while (true) {
            SearchFormDataIdListRequest searchFormDataIdListRequest = new SearchFormDataIdListRequest()
                    .setSystemToken(systemToken)
                    .setUserId(userId)
                    .setPageSize(pageSize)
                    .setPageNumber(pageNumber);

            try {
                var response = client.searchFormDataIdListWithOptions(appType, formUuid, searchFormDataIdListRequest, searchFormDataIdListHeaders, new com.aliyun.teautil.models.RuntimeOptions()).getBody();
                List<String> data = response.getData();
                if (data == null || data.isEmpty()) {
                    break;
                }
                instanceIdList.addAll(data);
                System.out.println(data);
                if (data.size() < pageSize) {
                    break;
                }
                pageNumber++;
            } catch (TeaException err) {
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    logger.error("getInstanceIdList Error code: {}, Error message: {}", err.code, err.message, err);
                }
                break;
            } catch (Exception _err) {
                TeaException err = new TeaException(_err.getMessage(), _err);
                if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                    // err 中含有 code 和 message 属性，可帮助开发定位问题
                    logger.error("getInstanceIdList Error code: {}, Error message: {}", err.code, err.message, err);
                }
                break;
            }
        }
        return instanceIdList;
    }


    /**
     * 根据实例ID获取实力详情数据
     **/
    public Map<String, ?> getInstance(String accessToken, String instanceId) throws Exception {
        Map<String, ?> formData = null;
        com.aliyun.dingtalkyida_2_0.Client client = createClient2();
        com.aliyun.dingtalkyida_2_0.models.GetInstanceByIdHeaders getFormDataByIDHeaders = new com.aliyun.dingtalkyida_2_0.models.GetInstanceByIdHeaders();
        getFormDataByIDHeaders.xAcsDingtalkAccessToken = accessToken;
        com.aliyun.dingtalkyida_2_0.models.GetInstanceByIdRequest getFormDataByIDRequest = new com.aliyun.dingtalkyida_2_0.models.GetInstanceByIdRequest()
                .setSystemToken("TL86618152F0MLOLCWS0L5NB50YR3QN8NU33L1")
                .setUserId("1837291108730155")
                .setAppType("APP_R0E06NSWHGKGCH1IZYEC");
        try {
            var response = client.getInstanceByIdWithOptions(instanceId, getFormDataByIDRequest, getFormDataByIDHeaders, new com.aliyun.teautil.models.RuntimeOptions()).getBody();
            String status = response.getInstanceStatus();
            if(status.equals("COMPLETED")){
                formData = response.getData();
                String modifiedTime = response.getModifiedTimeGMT();
                if (formData != null) {
                    ((Map<String, Object>) formData).put("modifiedTime", modifiedTime);
                }
            }

        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("getInstance Error code: {}, Error message: {}", err.code, err.message, err);
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                logger.error("getInstance Error code: {}, Error message: {}", err.code, err.message, err);
            }

        }
        return formData;
    }



    /**
     * 获取宜搭临时免登地址
     */

    @Override
    public String getAccessToken() {
        return new DingTalkAccessimpl().getAccessToken();
    }


    /**
     * 获取文件URL下载地址
     */



}
